e94252a758b20a8394053f52ac1a6ae63d564093
6 * @author Zhengzhu Feng <zhengzhu@gmail.com>
7 * @license http://www.gnu.org/copyleft/gpl.html GNU General Public License
10 class LanguageConverter
{
11 var $mPreferredVariant='';
12 var $mMainLanguageCode;
13 var $mVariants, $mVariantFallbacks;
14 var $mTablesLoaded = false;
16 var $mTitleDisplay='';
17 var $mDoTitleConvert=true, $mDoContentConvert=true;
24 * @param string $maincode the main language code of this language
25 * @param array $variants the supported variants of this language
26 * @param array $variantfallback the fallback language of each variant
27 * @param array $markup array defining the markup used for manual conversion
30 function LanguageConverter($langobj, $maincode,
32 $variantfallbacks=array(),
33 $markup=array('begin'=>'-{',
38 $this->mLangObj
= $langobj;
39 $this->mMainLanguageCode
= $maincode;
40 $this->mVariants
= $variants;
41 $this->mVariantFallbacks
= $variantfallbacks;
42 $this->mCacheKey
= $wgDBname . ":conversiontables";
43 $this->mMarkup
= $markup;
49 function getVariants() {
50 return $this->mVariants
;
54 * in case some variant is not defined in the markup, we need
55 * to have some fallback. for example, in zh, normally people
56 * will define zh-cn and zh-tw, but less so for zh-sg or zh-hk.
57 * when zh-sg is preferred but not defined, we will pick zh-cn
58 * in this case. right now this is only used by zh.
60 * @param string $v the language code of the variant
61 * @return string the code of the fallback language or false if there is no fallback
64 function getVariantFallback($v) {
65 return $this->mVariantFallbacks
[$v];
70 * get preferred language variants.
71 * @return string the preferred language code
74 function getPreferredVariant() {
75 global $wgUser, $wgRequest;
77 if($this->mPreferredVariant
)
78 return $this->mPreferredVariant
;
80 // see if the preference is set in the request
81 $req = $wgRequest->getText( 'variant' );
82 if( in_array( $req, $this->mVariants
) ) {
83 $this->mPreferredVariant
= $req;
87 // get language variant preference from logged in users
88 if(is_object($wgUser) && $wgUser->isLoggedIn() ) {
89 $this->mPreferredVariant
= $wgUser->getOption('variant');
92 # FIXME rewrite code for parsing http header. The current code
93 # is written specific for detecting zh- variants
94 if( !$this->mPreferredVariant
) {
95 // see if some zh- variant is set in the http header,
96 $this->mPreferredVariant
=$this->mMainLanguageCode
;
97 if(array_key_exists('HTTP_ACCEPT_LANGUAGE', $_SERVER)) {
98 $header = str_replace( '_', '-', strtolower($_SERVER["HTTP_ACCEPT_LANGUAGE"]));
99 $zh = strstr($header, 'zh-');
101 $this->mPreferredVariant
= substr($zh,0,5);
106 return $this->mPreferredVariant
;
110 * dictionary-based conversion
112 * @param string $text the text to be converted
113 * @param string $toVariant the target language code
114 * @return string the converted text
117 function autoConvert($text, $toVariant=false) {
118 $fname="LanguageConverter::autoConvert";
119 wfProfileIn( $fname );
121 if(!$this->mTablesLoaded
)
125 $toVariant = $this->getPreferredVariant();
126 if(!in_array($toVariant, $this->mVariants
))
131 $a = explode('<', $text);
132 $a0 = array_shift($a);
133 $ret .= strtr($a0, $this->mTables
[$toVariant]);
134 foreach( $a as $aa ) {
135 $b = explode('>', $aa, 2);
138 $ret .= '>' . strtr($b[1], $this->mTables
[$toVariant]);
141 # /* put back the marker if any */
143 # $reg = '<'.$reg.'>';
144 # $ret = preg_replace('/'.$reg.'/', '${1}', $ret);
147 wfProfileOut( $fname );
152 * convert text to all supported variants
154 * @param string $text the text to be converted
155 * @return array of string
158 function autoConvertToAllVariants($text) {
159 $fname="LanguageConverter::autoConvertToAllVariants";
160 wfProfileIn( $fname );
161 if( !$this->mTablesLoaded
)
165 foreach($this->mVariants
as $variant) {
166 $ret[$variant] = strtr($text, $this->mTables
[$variant]);
168 wfProfileOut( $fname );
173 * convert text to different variants of a language. the automatic
174 * conversion is done in autoConvert(). here we parse the text
175 * marked with -{}-, which specifies special conversions of the
176 * text that can not be accomplished in autoConvert()
178 * syntax of the markup:
179 * -{code1:text1;code2:text2;...}- or
180 * -{text}- in which case no conversion should take place for text
182 * @param string $text text to be converted
183 * @param bool $isTitle whether this conversion is for the article title
184 * @return string converted text
187 function convert( $text , $isTitle=false) {
188 global $wgDisableLangConversion;
189 if($wgDisableLangConversion)
192 $mw =& MagicWord
::get( MAG_NOTITLECONVERT
);
193 if( $mw->matchAndRemove( $text ) )
194 $this->mDoTitleConvert
= false;
196 $mw =& MagicWord
::get( MAG_NOCONTENTCONVERT
);
197 if( $mw->matchAndRemove( $text ) ) {
198 $this->mDoContentConvert
= false;
201 // no conversion if redirecting
202 $mw =& MagicWord
::get( MAG_REDIRECT
);
203 if( $mw->matchStart( $text ))
207 if( !$this->mDoTitleConvert
) {
208 $this->mTitleDisplay
= $text;
211 if( !empty($this->mTitleDisplay
))
212 return $this->mTitleDisplay
;
215 $isredir = $wgRequest->getText( 'redirect', 'yes' );
216 $action = $wgRequest->getText( 'action' );
217 if ( $isredir == 'no' ||
$action == 'edit' ) {
221 $this->mTitleDisplay
= $this->autoConvert($text);
222 return $this->mTitleDisplay
;
226 if( !$this->mDoContentConvert
)
229 $search = array('/('.UNIQ_PREFIX
.'-[a-zA-Z0-9]+)/', //nowiki marker
230 '/(&[a-z#][a-z0-9]+;)/', //html entities
232 $replace = $this->mMarkup
['begin'].'${1}'.$this->mMarkup
['end'];
234 $text = preg_replace($search, $replace, $text);
236 $plang = $this->getPreferredVariant();
237 $fallback = $this->mVariantFallbacks
[$plang];
238 $tarray = explode($this->mMarkup
['begin'], $text);
239 $tfirst = array_shift($tarray);
240 $text = $this->autoConvert($tfirst);
241 foreach($tarray as $txt) {
242 $marked = explode($this->mMarkup
['end'], $txt);
244 # FIXME: this may cause trouble...
245 //strip since it interferes with the parsing, plus,
246 //all spaces should be stripped in this tag anyway.
247 $marked[0] = str_replace(' ', '', $marked[0]);
249 /* see if this conversion has special meaning
251 -{T|zh-cn:foo;zh-tw:bar}-
252 # convert all occurence of foo/bar in this article:
253 -{A|zh-cn:foo;zh-tw:bar}-
257 $tt = explode("|", $marked[0], 2);
258 if(sizeof($tt) == 2) {
259 $flag = trim($tt[0]);
260 $choice = explode(";", $tt[1]);
264 $choice = explode($this->mMarkup
['varsep'], $marked[0]);
268 if(!array_key_exists(1, $choice)) {
269 /* a single choice */
272 /* fill the carray if the conversion is for the whole article*/
274 foreach($this->mVariants
as $v) {
280 foreach($choice as $c) {
281 $v = explode($this->mMarkup
['codesep'], $c);
282 if(sizeof($v) != 2) // syntax error, skip
284 $carray[trim($v[0])] = trim($v[1]);
286 if(array_key_exists($plang, $carray))
287 $disp = $carray[$plang];
288 else if(array_key_exists($fallback, $carray))
289 $disp = $carray[$fallback];
291 if(empty($disp)) { // syntax error
295 if($flag == 'T') // for title only
296 $this->mTitleDisplay
= $disp;
300 /* modify the conversion table for this session*/
302 /* fill in the missing variants, if any,
304 foreach($this->mVariants
as $v) {
305 if(!array_key_exists($v, $carray)) {
306 $vf = $this->getVariantFallback($v);
307 if(array_key_exists($vf, $carray))
308 $carray[$v] = $carray[$vf];
311 foreach($this->mVariants
as $vfrom) {
312 if(!array_key_exists($vfrom, $carray))
314 foreach($this->mVariants
as $vto) {
317 if(!array_key_exists($vto, $carray))
319 $this->mTables
[$vto][$carray[$vfrom]] = $carray[$vto];
325 if(array_key_exists(1, $marked))
326 $text .= $this->autoConvert($marked[1]);
334 * if a language supports multiple variants, it is
335 * possible that non-existing link in one variant
336 * actually exists in another variant. this function
337 * tries to find it. See e.g. LanguageZh.php
339 * @param string $link the name of the link
340 * @param mixed $nt the title object of the link
341 * @return null the input parameters may be modified upon return
344 function findVariantLink( &$link, &$nt ) {
345 static $count=0; //used to limit this operation
346 static $cache=array();
347 global $wgDisableLangConversion;
348 $pref = $this->getPreferredVariant();
352 $variants = $this->autoConvertToAllVariants($link);
353 if($variants == false) //give up
355 foreach( $variants as $v ) {
356 if(isset($cache[$v]))
359 $varnt = Title
::newFromText( $v );
360 if( $varnt && $varnt->getArticleID() > 0 ) {
362 if( !$wgDisableLangConversion && $pref != 'zh' )
370 * returns language specific hash options
374 function getExtraHashOptions() {
375 $variant = $this->getPreferredVariant();
376 return '!' . $variant ;
380 * get title text as defined in the body of the article text
384 function getParsedTitle() {
385 return $this->mTitleDisplay
;
389 * a write lock to the cache
393 function lockCache() {
396 for($i=0; $i<30; $i++
) {
397 if($success = $wgMemc->add($this->mCacheKey
. "lock", 1, 10))
409 function unlockCache() {
411 $wgMemc->delete($this->mCacheKey
. "lock");
416 * Load default conversion tables
417 * This method must be implemented in derived class
421 function loadDefaultTables() {
422 $name = get_class($this);
423 die("Must implement loadDefaultTables() method in class $name");
427 * load conversion tables either from the cache or the disk
430 function loadTables($fromcache=true) {
432 if( $this->mTablesLoaded
)
434 $this->mTablesLoaded
= true;
436 $this->mTables
= $wgMemc->get( $this->mCacheKey
);
437 if( !empty( $this->mTables
) ) //all done
440 // not in cache, or we need a fresh reload.
441 // we will first load the default tables
442 // then update them using things in MediaWiki:Zhconversiontable/*
443 global $wgMessageCache;
444 $this->loadDefaultTables();
445 foreach($this->mVariants
as $var) {
446 $cached = $this->parseCachedTable($var);
447 $this->mTables
[$var] = array_merge($this->mTables
[$var], $cached);
450 $this->postLoadTables();
452 if($this->lockCache()) {
453 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
454 $this->unlockCache();
459 * Hook for post processig after conversion tables are loaded
462 function postLoadTables() {}
465 function updateTablexxxx($code, $table) {
467 if(!$this->mTablesLoaded
)
470 $this->mTables
[$code] = array_merge($this->mTables
[$code], $table);
471 if($this->lockCache()) {
472 $wgMemc->delete($this->mCacheKey
);
473 $wgMemc->set($this->mCacheKey
, $this->mTables
, 43200);
474 $this->unlockCache();
479 * Reload the conversion tables
483 function reloadTables() {
485 unset($this->mTables
);
486 $this->mTablesLoaded
= false;
487 $this->loadTables(false);
492 * parse the conversion table stored in the cache
494 * the tables should be in blocks of the following form:
502 * to make the tables more manageable, subpages are allowed
503 * and will be parsed recursively if $recursive=true
507 function parseCachedTable($code, $subpage='', $recursive=true) {
508 global $wgMessageCache;
509 static $parsed = array();
511 if(!is_object($wgMessageCache))
514 $key = 'Conversiontable/'.$code;
516 $key .= '/' . $subpage;
518 if(array_key_exists($key, $parsed))
522 $txt = $wgMessageCache->get( $key, true, true, true );
524 // get all subpage links of the form
525 // [[MediaWiki:conversiontable/zh-xx/...|...]]
526 $linkhead = $this->mLangObj
->getNsText(NS_MEDIAWIKI
) . ':Conversiontable';
527 $subs = explode('[[', $txt);
529 foreach( $subs as $sub ) {
530 $link = explode(']]', $sub, 2);
531 if(count($link) != 2)
533 $b = explode('|', $link[0]);
534 $b = explode('/', trim($b[0]), 3);
540 if($b[0] == $linkhead && $b[1] == $code) {
541 $sublinks[] = $sublink;
546 // parse the mappings in this page
547 $blocks = explode('-{', $txt);
548 array_shift($blocks);
550 foreach($blocks as $block) {
551 $mappings = explode('}-', $block, 2);
552 $stripped = str_replace(array("'", '"', '*','#'), '', $mappings[0]);
553 $table = explode( ';', $stripped );
554 foreach( $table as $t ) {
555 $m = explode( '=>', $t );
556 if( count( $m ) != 2)
558 // trim any trailling comments starting with '//'
559 $tt = explode('//', $m[1], 2);
560 $ret[trim($m[0])] = trim($tt[0]);
563 $parsed[$key] = true;
566 // recursively parse the subpages
568 foreach($sublinks as $link) {
569 $s = $this->parseCachedTable($code, $link, $recursive);
570 $ret = array_merge($ret, $s);
577 * Enclose a string with the "no conversion" tag. This is used by
578 * various functions in the Parser
580 * @param string $text text to be tagged for no conversion
581 * @return string the tagged text
583 function markNoConversion($text) {
584 $ret = $this->mMarkup
['begin'] . $text . $this->mMarkup
['end'];
589 * hook to refresh the cache of conversion tables when
590 * MediaWiki:conversiontable* is updated
593 function OnArticleSaveComplete($article, $user, $text, $summary, $isminor, $iswatch, $section) {
594 $titleobj = $article->getTitle();
595 if($titleobj->getNamespace() == NS_MEDIAWIKI
) {
597 global $wgContLang; // should be an LanguageZh.
598 if(get_class($wgContLang) != 'languagezh')
601 $title = $titleobj->getDBkey();
602 $t = explode('/', $title, 3);
604 if( $c > 1 && $t[0] == 'Conversiontable' ) {
605 if(in_array($t[1], $this->mVariants
)) {
606 $this->reloadTables();